// pages/play/play.js
var hotapp = require('../../utils/hotapp.js')
Page({
  data: {
    hash: '', // 初始化歌曲hash
    fileName: '', // 初始化文件名称
    playUrl: '', // 初始化歌曲播放地址
    imgUrl: '', // 初始化歌曲封面图片地址
    singer: '', // 初始化歌手
    audo: {}, // 初始化背景音乐播放器
    timeLen: '', // 初始化歌曲长度 （毫秒）
    progLine: '', // 初始化播放进度条
    progLineNum: 1, // 初始化进度条数字
    timer: {}, // 初始化进度条计时器
    timeStr: '', // 初始化歌曲时间 （分： 秒）
    countTime: '',
    playMs: 0,
    playS: 0, // 初始化歌曲时间 （秒）
    playM: 0, // 初始化歌曲时间 （分）
    playTimer: {}, // 初始化播放时间计时器
    imgShow: 'block',
    lyricsShow: 'none',
    only_lyr_arr: '', // 初始化歌词对应时间
    only_lyr_time: [], // 初始化纯歌词
    lyrPosition: 0, // 初始化歌词位置
    lryTimer: {}, // 初始化歌词定时器
    lyrMs: 0,
    lyrSec: 0,
    lyrM: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取并设置歌曲播放hash
    let getHash = options.hash
    this.setData({
      hash: getHash
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    let songHash = this.data.hash
    let play_url = `http://www.cmslz.com/music/index/getDesc?hash=${songHash}`
    // 请求歌曲详细信息
    hotapp.request({
      useProxy: true,
      url: play_url,
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.statusCode == 200) {
          // 获取歌曲信息
          let singer = res.data.data.author_name
          let musicName = res.data.data.song_name
          let img = res.data.data.img
          let playUrl = res.data.data.play_url
          let timeLen = res.data.data.timelength
          let lyrics = res.data.data.lyrics

          // 创建背景音乐播放器
          const ad = wx.getBackgroundAudioManager()
          ad.title = musicName
          ad.epname = musicName
          ad.singer = singer
          ad.coverImgUrl = img
          ad.src = playUrl

          let reg = /\[(.+?)\]/g // 设置正则匹配中括号内容，包括中括号
          let only_lyr = lyrics.replace(reg, '') // 获取纯中文歌词
          let only_lyr_time = lyrics.match(reg) // 获取歌词时间
          let only_lyr_arr = only_lyr.split('\n') // 分割歌词字符串
          only_lyr_arr.pop() // 删除歌词数组中最后一个空元素
          that.setData({
            singer: singer,
            imgUrl: img,
            playUrl: playUrl,
            fileName: musicName,
            audo: ad,
            timeLen: timeLen,
            only_lyr_arr: only_lyr_arr,
            only_lyr_time: only_lyr_time
          })

          // 执行计时器
          that.timeRuner()
          that.timeChange()
          that.playTimer()
          that.lyrPlay()
        } else {
          console.log('播放音乐失败')
        }
      }
    })
  },
  playMusic: function () {
    // 手动播放
    this.data.audo.play()
    this.timeRuner()
    this.playTimer()
    this.lyrPlay()
  },
  stopMusic: function () {
    // 手动停止
    this.data.audo.pause()
    clearTimeout(this.data.timer)
    clearTimeout(this.data.playTimer)
    clearTimeout(this.data.lryTimer)
  },
  timeRuner: function () {
    // 动态更新进度条进度
    let that = this
    let num = that.data.progLineNum
    let timeLen = that.data.timeLen // 获取歌曲时长(毫秒)

    // 动态更新进度条
    var timer = setInterval(() => {
      if (that.data.progLineNum >= 100) {
        that.setData({
          progLineNum: 1
        })
        num = 1
        clearTimeout(this.data.timer)
      }
      that.setData({
        progLine: `${num}%`,
        progLineNum: num
      })
      num++
    }, ~~(timeLen / 100))
    that.setData({
      timer: timer
    })
  },
  timeChange: function () {
    // 转换时间
    let that = this
    let d = new Date(that.data.timeLen)
    let m = d.getMinutes()
    let s = d.getSeconds()
    let ms = d.getMilliseconds()
    let timeStr = `${m}:${s}:${ms}`
    let countStr = `${m}:${s}`
    that.setData({
      timeStr: timeStr,
      countTime: countStr
    })
  },
  playTimer: function () {
    // 动态更新歌曲播放时间
    let that = this
    let timeS = that.data.playS
    let timeM = that.data.playM
    let timer = setInterval(() => {
      if (timeS >= 60) {
        timeS = 0
        timeM++
      }
      that.setData({
        playS: timeS,
        playM: timeM
      })
      timeS++
    }, 1000)
    that.setData({
      playTimer: timer
    })
    that.data.audo.onEnded(function () {
      // 歌曲播放结束
      clearTimeout(that.data.playTimer)
      clearTimeout(that.data.timeRuner)
      clearTimeout(that.data.lryTimer)
      that.setData({
        playS: 0,
        playM: 0,
        progLineNum: 1,
        progLine: '1%',
        lyrMs: 0,
        lyrSec: 0,
        lyrM: 0
      })
    })
  },
  changeLine: function (e) {
    // 操作播放进度
    let that = this

    // 获取歌曲时间长度
    let t = that.data.timeStr
    let strArr = t.split(':')
    let m = parseInt(strArr[0])
    let s = parseInt(strArr[1])
    let ms = parseInt(strArr[2])
    let count = ~~(m * 60 + s)

    let count_ms = count * 1000 + ms // 获得总毫秒数

    let query = wx.createSelectorQuery()
    query.select('#prog').boundingClientRect()
    query.exec(function (res) {
      if (res) {
        // 获取进度条点击位置
        let parentWidth = res[0].width
        let tapPosition = e.detail.x - res[0].left
        // 得到点击位置相对百分比
        let presen = ~~((tapPosition / parentWidth).toFixed(2) * 100)
        // 计算占进度条的百分比
        let playPosition = Math.ceil(count * (presen / 100))
        // 另外计算毫秒
        let p_ms = Math.ceil(count_ms * (presen / 100))
        
        // 计算对应的播放时间
        let c_s = playPosition % 60 // 计算秒
        let c_m = ~~(playPosition / 60) // 计算分
        // 另外计算毫秒
        let c_ms = p_ms % 60


        // 更新进度条以及设置播放位置
        clearTimeout(that.data.timer)
        clearTimeout(that.data.playTimer)
        that.setData({
          progLine: `${presen}%`,
          progLineNum: presen,
          playS: c_s,
          playM: c_m,
          playMs: c_ms
        })
        clearTimeout(that.data.lryTimer)
        that.lyrPlay(true)
        that.data.audo.seek(playPosition)
        that.timeRuner()
        that.playTimer()
      } else {
        console.log('操作失败')
      }
    })
  },
  show_hidden: function (e) {
    // 歌曲封面以及歌词相互切换
    let imgShow = this.data.imgShow
    if (imgShow == 'block') {
      this.setData({
        imgShow: 'none',
        lyricsShow: 'block'
      })
    } else {
      this.setData({
        imgShow: 'block',
        lyricsShow: 'none'
      })
    }
  },
  lyrPlay: function (jump) {
    // 设置歌词轮播
    let that = this
    let timeArr = this.data.only_lyr_time // 获取时间数组
    let ms = that.data.playMs  // 毫秒
    let sec = that.data.playS // 秒
    let m = that.data.playM // 分

    let lyrLineHeight = 21 // 设置歌词每秒滚动高度
    let position = that.data.lyrPosition
    let sec_str, ms_str, m_str, time_str // 设置计时器字符串

    let lyrTimer = setInterval(() => {
      if (ms >= 100) {
        sec += 1
        ms = 0
      }
      if (sec >= 60) {
        m += 1
        sec = 0
      }
      // 设置字符串格式,与转换后的歌词格式想对应
      ms < 10 ? ms_str = `0${ms}` : ms_str = `${ms}`
      sec < 10 ? sec_str = `0${sec}` : sec_str = `${sec}`
      m < 10 ? m_str = `0${m}` : m_str = `${m}`
      time_str = `[${m_str}:${sec_str}.${ms_str}]`

      if (jump) {
        for (let l = 0, len = timeArr.length; l < len; l++) {
          if (time_str == timeArr[l]) {
            position = 21 * l
            that.setData({
              lyrPosition: position
            })
          }
        }
      }

      // 更新计时器时间
      that.setData({
        lyrMs: ms,
        lyrM: m,
        lyrSec: sec
      })

      // 动态更新歌词位置
      for (let i = 0, len = timeArr.length; i < len; i++) {
        if (time_str == timeArr[i]) {
          position = 21 * i
          that.setData({
            lyrPosition: position
          })
        }
      }
      ms += 1
    }, 10)
    that.setData({
      lryTimer: lyrTimer
    })
  }
})